package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApCollectionService;
import com.heima.article.service.AuthorService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.article.dto.ArticleHomeDto;
import com.heima.model.article.dto.ArticleInfoDto;
import com.heima.model.article.pojos.*;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.ArticleVisitStreamMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.utils.threadlocal.AppUserThreadLocalUtils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    AuthorService authorService;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    UserFeign userFeign;
    @Autowired
    ApCollectionService apCollectionService;
    @Autowired
    RedisTemplate<String, String> redisTemplate;


    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    @Transactional
    public ResponseResult saveArtilce(ArticleDto articleDto) {
        //验证参数
        if (articleDto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //封装article对象
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        //根据作者名称查询作者id
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, articleDto.getAuthorName()));
        if (apAuthor == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章作者不存在");
        }
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        //判断文章是否存在
        if (apArticle.getId() == null) {
            // 普通文章
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            save(apArticle);
        } else {
            ApArticle one = getById(apArticle.getId());
            if (one == null) {
                log.error("对应文章id的文章不存在，文章id为==>{}", apArticle.getId());
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章数据不存在");
            }
            //删除中间表相关信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            updateById(apArticle);
        }
        //插入中间表文章配置表
        //保存article_config 数据
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfigMapper.insert(apArticleConfig);
        //添加文章内容
        //保存文章article_content 数据
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(articleDto.getContent());
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContentMapper.insert(apArticleContent);
        //返回文章ID
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getSize() == null || dto.getSize() < 1 || dto.getSize() > 50) {
            dto.setSize(10);
        }
        //设置频道id信息
        if (dto.getTag() == null) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //判断请求参数中的时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //判断查询类型
        if (loadtype == null || (loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW))) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //查询文章列表
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, loadtype);
        ResponseResult responseResult = ResponseResult.okResult(apArticleList);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 加载文章详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long articleId = dto.getArticleId();
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(
                Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, articleId));
        if (apArticleConfig == null || apArticleConfig.getIsDelete() || apArticleConfig.getIsDown()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已下架");
        }
        //根据文章id查询文章内容和文章配置
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(
                Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleId));
        if (apArticleContent == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章内容信息不存在");
        }
        Map map = new HashMap();
        map.put("config", apArticleConfig);
        map.put("content", apArticleContent);
        return ResponseResult.okResult(map);
    }

    /**
     * 获取文章中用户的行为数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        Map resultMap = new HashMap();
        resultMap.put("islike", false);
        resultMap.put("isunlike", false);
        resultMap.put("isfollow", false);
        resultMap.put("iscollection", false);
        //参数校验
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.okResult(resultMap);
        }
        //判断用户的登录状态
        ApUser user = AppUserThreadLocalUtils.getUser();
        ApArticleRelationDto apArticleRelationDto = new ApArticleRelationDto();
        if (user != null) {
            //用户登录
            apArticleRelationDto.setEntryId(user.getId());
            apArticleRelationDto.setType((short) 1);
            //判断是否关注了作者,只有登录用户才能关注作者
            ApUserFollow apUserFollow = userFeign.findByUserIdAndFollowId(user.getId(), dto.getAuthorId());
            if (apUserFollow != null) {
                resultMap.put("isfollow", true);
            }
        } else {
            //设备id登录
            apArticleRelationDto.setEntryId(dto.getEquipmentId());
            apArticleRelationDto.setType((short) 0);
        }
        apArticleRelationDto.setArticleId(dto.getArticleId());
        //远程调用方法查询是否点赞和不喜欢
        Map map = behaviorFeign.findApArticleRelation(apArticleRelationDto);
        resultMap.putAll(map);
        //判断是否收藏
        ApCollection apCollection = apCollectionService.getOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getArticleId, dto.getArticleId())
                .eq(ApCollection::getEntryId, map.get("entryId")));
        if (apCollection != null) {
            resultMap.put("iscollection", true);
        }
        return ResponseResult.okResult(resultMap);

    }

    /**
     * 计算新增行为影响的文章得分及更新redis数据
     *
     * @param articleVisitStreamMess
     */
    @Override
    public void updateApArticle(ArticleVisitStreamMess articleVisitStreamMess) {
        //解析文章行为对象
        Long articleId = articleVisitStreamMess.getArticleId();
        //根据文章id获取文章
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.info("计算得分更新redis数据方法，根据文章id获取文章数据失败 {}", articleId);
            return;
        }
        //修改数据库文章行为参数并计算得分获取存入redis数据库的对象
        HotArticleVo hotArticleVo = updateApArticleByAction(articleVisitStreamMess, apArticle);
        //更新数据库热点文章
        //更新频道热点文章
        updateRedisArticle(hotArticleVo, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + hotArticleVo.getChannelId());
        //更新推荐也热点文章
        updateRedisArticle(hotArticleVo, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 根据参数加载文章列表  v2
     *
     * @param loadtypeLoadMore
     * @param dto
     * @param firstPage
     * @return
     */
    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDto dto, boolean firstPage) {
        if (firstPage) {
            String jsonStr = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(jsonStr)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                if (!hotArticleVoList.isEmpty() && hotArticleVoList.size() > 0) {
                    ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                    responseResult.setHost(webSite);
                    return responseResult;
                }
            }
        }
        return load(loadtypeLoadMore, dto);
    }

    /**
     * 更新redis数据热点文章方法
     * @param hotArticleVo
     */
    private void updateRedisArticle(HotArticleVo hotArticleVo, String cacheKey) {
        //获取热点文章集合
        String hotArticleListJson = redisTemplate.opsForValue().get(cacheKey);
        List<HotArticleVo> hotArticleVoList = JSONArray.parseArray(hotArticleListJson, HotArticleVo.class);
        boolean flag = false;
        //判断集合中是否存在该文章，存在的话更新分数
        for (HotArticleVo articleVo : hotArticleVoList) {
            if (articleVo.getId().equals(hotArticleVo.getId())) {
                articleVo.setScore(hotArticleVo.getScore());
                flag = true;
                break;
            }
        }
        if (flag == false) {
            //将数据直接插入redis，再重新给redis数据库数据排序获取前三十
            hotArticleVoList.add(hotArticleVo);
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());
        }
        //存入到redis中
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVoList));
    }

    /**
     * 修改文章表行为数据
     *
     * @param articleVisitStreamMess
     * @param apArticle
     */
    private HotArticleVo updateApArticleByAction(ArticleVisitStreamMess articleVisitStreamMess, ApArticle apArticle) {
        //调用计算文章分数方法
        Integer score = computeScore(articleVisitStreamMess,apArticle);
        //判断行为是哪一项
        if (articleVisitStreamMess.getView() != 0) {
            if (apArticle.getViews() == null) {
                //为空直接设置
                apArticle.setViews(Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getView())));
            } else {//不为空相加
                apArticle.setViews(apArticle.getViews() + Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getView())));
            }
//            hotArticleVo.setViews(Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getView())));
        }

        if (articleVisitStreamMess.getLike() != 0) {
            if (apArticle.getLikes() == null) {
                //为空直接设置
                apArticle.setLikes(Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getLike())));
            } else {//不为空相加
                apArticle.setLikes(apArticle.getLikes() + Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getLike())));
            }
//            hotArticleVo.setLikes(Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getLike())));
        }

        if (articleVisitStreamMess.getComment() != 0) {
            if (apArticle.getComment() == null) {
                //为空直接设置
                apArticle.setComment(Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getComment())));
            } else {//不为空相加
                apArticle.setComment(apArticle.getComment() + Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getComment())));
            }
//            hotArticleVo.setComment(Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getComment())));
        }

        if (articleVisitStreamMess.getCollect() != 0) {
            if (apArticle.getCollection() == null) {
                //为空直接设置
                apArticle.setCollection(Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getCollect())));
            } else {//不为空相加
                apArticle.setCollection(apArticle.getCollection() + Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getCollect())));
            }
//            hotArticleVo.setCollection(Integer.valueOf(JSON.toJSONString(articleVisitStreamMess.getCollect())));
        }
        //更新数据文章数据
        updateById(apArticle);

        HotArticleVo hotArticleVo = new HotArticleVo();
        BeanUtils.copyProperties(apArticle, hotArticleVo);
        hotArticleVo.setScore(score);
        return hotArticleVo;
    }

    /**
     * 计算文章得分
     *
     * @param articleVisitStreamMess
     * @return
     */
    private Integer computeScore(ArticleVisitStreamMess articleVisitStreamMess,ApArticle apArticle) {
        //计算文章原得分
        Integer score = 0;
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        //计算当前行为产生的分数
        Integer nowDayScore = 0;
        if (articleVisitStreamMess.getView() != 0) {
            nowDayScore += (int) articleVisitStreamMess.getView() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        if (articleVisitStreamMess.getLike() != 0) {
            nowDayScore += (int) articleVisitStreamMess.getLike() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (articleVisitStreamMess.getComment() != 0) {
            nowDayScore += (int) articleVisitStreamMess.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (articleVisitStreamMess.getCollect() != 0) {
            nowDayScore += (int) articleVisitStreamMess.getCollect() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score + nowDayScore * 3;
    }
}
